#!/usr/bin/env python
#
# Generally called by package-all-ipp-printers.sh in a loop to generate a
# pkgsinfo descriptor file representing a printer.
#
# This script is responsible for generating the appropriate install, 
# verification, and uninstallation scripts that Munki needs to control print
# objects on local machines.
#
import sys
import os
import tempfile
import shutil
import subprocess
import plistlib
import re
from urlparse import urlparse

if len(sys.argv) < 4:
	sys.stderr.write('Usage: %s <ipp-url> <version>\n' % (sys.argv[0]))
	sys.stderr.write('       ipp-url: e.g. ipp://140.141.2.150/ipp/MathSci217_HP4300N_Printer\n')
	sys.stderr.write('       description: e.g. "This printer is located in 7th hell."\n')
	sys.stderr.write('       version: Desired version of the resulting package.\n')
	sys.exit(1)






ipp_url = sys.argv[1];
pkgDescription = sys.argv[2];
thePkgVersion = sys.argv[3];
thePkgName = os.path.basename(urlparse(ipp_url).path)
_prefs = plistlib.readPlist(os.path.expanduser("~/Library/Preferences/com.googlecode.munki.munkiimport.plist"))
OUTPUT_PATH = _prefs['repo_path'] + '/pkgsinfo/printers/' + re.sub("\d+$","",thePkgName) + '-' + thePkgVersion

theInstallCheckScript = "#!/bin/bash\n"
theInstallCheckScript += "/usr/bin/lpstat -a | grep \"%s\"\n" % thePkgName
theInstallCheckScript += "exit $?"


thePreinstallScript = "#!/bin/bash\n"
thePreinstallScript += "/usr/bin/iprntcmd --addprinter \"%s\"" % ipp_url


theUninstallScript = "#!/bin/bash\n"
theUninstallScript += "/usr/sbin/lpadmin -x \"%s\"" % thePkgName


theUninstallCheckScript = "#!/bin/bash\n"
theUninstallCheckScript += "/usr/bin/lpstat -a | grep \"%s\"\n" % thePkgName
theUninstallCheckScript += "if [ \"${?}\" == \"0\" ]; then\n"
theUninstallCheckScript += "	exit 1\n"
theUninstallCheckScript += "else\n"
theUninstallCheckScript += "	exit 0\n"
theUninstallCheckScript += "fi"

pkginfo = dict(
    unattended_install = True,
		catalogs = ["production"],
		name = thePkgName,
		description = pkgDescription,
		requires = ["iPrint"],
		minimum_os_version = "10.6.8",
		installer_type = "nopkg",
		uninstallable = True,
		uninstall_method = "uninstall_script",
		uninstall_script = theUninstallScript,
		preinstall_script = thePreinstallScript,
		uninstallcheck_script = theUninstallCheckScript,
		installcheck_script = theInstallCheckScript,
		version = thePkgVersion
)

plistlib.writePlist(pkginfo, OUTPUT_PATH)

sys.stdout.write('\n====================================\n')
sys.stdout.write('    ipp-url: %s\n' % ipp_url)
sys.stdout.write('    version: %s\n' % thePkgVersion)
sys.stdout.write('       name: %s\n' % thePkgName)
sys.stdout.write('description: %s\n' % pkgDescription)
sys.stdout.write('      plist: %s\n' % OUTPUT_PATH)
sys.stdout.write('====================================\n')
